package org.smarthings.things.automation.rest.test;

import org.smarthings.things.automation.Action;
import org.smarthings.things.automation.Condition;
import org.smarthings.things.automation.Rule;
import org.smarthings.things.automation.Trigger;

public class RuleBuilder {

	private DefaultRule rule;

	private RuleBuilder() {
		this.rule = new DefaultRule();
	}

	public static RuleBuilder create() {
		return new RuleBuilder();
	}
	
	public RuleBuilder name(String name) {
		this.rule.setName(name);
		return this;
	}

	public RuleBuilder tags(String[] tags) {
		this.rule.setTags(tags);
		return this;
	}

	public RuleBuilder trigger(Trigger trigger) {
		this.rule.setTrigger(trigger);
		return this;
	}

	public RuleBuilder condition(String language, String script) {
		if (script != null) {
			this.rule.setCondition(new Condition(language, script));
		}
		return this;
	}

	public RuleBuilder condition(Condition condition) {
		this.rule.setCondition(condition);
		return this;
	}

	public RuleBuilder action(String language, String script) {
		this.rule.setAction(new Action(language, script));
		return this;
	}

	public RuleBuilder action(Action action) {
		this.rule.setAction(action);
		return this;
	}
	
	public RuleBuilder state(boolean state) {
		this.rule.setActiveSate(state);
		return this;
	}

	public Rule build() {
		return rule;
	}

	private class DefaultRule implements Rule {

		private String UUID;
		private Trigger trigger;
		private Condition condition;
		private Action action;
		private boolean state = true;
		private String name;
		private String[] tags;

		public DefaultRule() {
			this.UUID = generateRuleUUID();
		}

		public String getUUID() {
			return UUID;
		}

		public Trigger getTrigger() {
			return trigger;
		}

		public void setTrigger(Trigger trigger) {
			this.trigger = trigger;
		}

		public Condition getCondition() {
			return condition;
		}

		public void setCondition(Condition condition) {
			this.condition = condition;
		}

		public Action getAction() {
			return action;
		}

		public void setAction(Action action) {
			this.action = action;
		}

		@Override
		public boolean getActiveState() {
			return state;
		}

		@Override
		public void setActiveSate(boolean state) {
			this.state = state;
		}
		
		@Override
		public String getName() {
			return name;
		}

		@Override
		public String[] getTags() {
			return tags;
		}

		@Override
		public void setTags(String[] tags) {
			this.tags = tags;
		}

		@Override
		public void setName(String name) {
			this.name = name;
		}


	}

	private static long index = 0;

	private static String generateRuleUUID() {
		return String.valueOf(++index); // FIXME
		// return UUID.randomUUID().toString();
	}

}
